import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import { Table, Button, Space, message, Popconfirm, Tag, Input, Form } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, SearchOutlined } from '@ant-design/icons';
import { history } from 'umi';

const { Search } = Input;

const PermissionListPage: React.FC = () => {
  const [permissions, setPermissions] = useState([]);
  const [loading, setLoading] = useState(false);
  const [searchForm] = Form.useForm();

  useEffect(() => {
    fetchPermissions();
  }, []);

  const fetchPermissions = async (params: any = {}) => {
    setLoading(true);
    try {
      // TODO: Replace with actual API call
      // const response = await fetch('/api/permissions', { params });
      // const data = await response.json();
      
      // Mock data for now
      const mockData = [
        { 
          id: 1, 
          name: '用户管理', 
          code: 'user:manage', 
          type: 'menu',
          path: '/user',
          status: 1,
          createTime: '2023-05-20 10:00:00'
        },
        { 
          id: 2, 
          name: '角色管理', 
          code: 'role:manage', 
          type: 'menu',
          path: '/role',
          status: 1,
          createTime: '2023-05-20 10:00:00'
        },
        { 
          id: 3, 
          name: '权限管理', 
          code: 'permission:manage', 
          type: 'menu',
          path: '/permission',
          status: 1,
          createTime: '2023-05-20 10:00:00'
        },
      ];
      
      // Filter based on search params
      let filteredData = [...mockData];
      if (params.name) {
        filteredData = filteredData.filter(item => 
          item.name.includes(params.name)
        );
      }
      if (params.code) {
        filteredData = filteredData.filter(item => 
          item.code.includes(params.code)
        );
      }
      
      setPermissions(filteredData);
    } catch (error) {
      message.error('获取权限列表失败');
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = (values: any) => {
    fetchPermissions(values);
  };

  const handleReset = () => {
    searchForm.resetFields();
    fetchPermissions();
  };

  const handleAdd = () => {
    history.push('/permission/create');
  };

  const handleEdit = (id: number) => {
    history.push(`/permission/edit/${id}`);
  };

  const handleDelete = async (id: number) => {
    try {
      // TODO: Replace with actual API call
      // await fetch(`/api/permissions/${id}`, { method: 'DELETE' });
      message.success('删除成功');
      fetchPermissions(searchForm.getFieldsValue());
    } catch (error) {
      message.error('删除失败');
    }
  };

  const columns = [
    {
      title: '权限名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '权限标识',
      dataIndex: 'code',
      key: 'code',
      render: (code: string) => <Tag color="blue">{code}</Tag>,
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (type: string) => {
        const typeMap = {
          menu: { text: '菜单', color: 'green' },
          button: { text: '按钮', color: 'orange' },
          api: { text: '接口', color: 'purple' },
        };
        const typeInfo = typeMap[type as keyof typeof typeMap] || { text: type, color: 'default' };
        return <Tag color={typeInfo.color}>{typeInfo.text}</Tag>;
      },
    },
    {
      title: '路径',
      dataIndex: 'path',
      key: 'path',
      render: (path: string) => path || '-',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: number) => (
        <Tag color={status === 1 ? 'success' : 'error'}>
          {status === 1 ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: any) => (
        <Space size="middle">
          <Button 
            type="link" 
            icon={<EditOutlined />} 
            onClick={() => handleEdit(record.id)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个权限吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer
      header={{
        title: '权限管理',
        breadcrumb: {
          items: [
            { title: '系统管理' },
            { title: '权限管理' },
          ],
        },
      }}
      extra={[
        <Button 
          key="add" 
          type="primary" 
          icon={<PlusOutlined />} 
          onClick={handleAdd}
        >
          新建权限
        </Button>,
      ]}
    >
      <Card>
        <Form
          form={searchForm}
          layout="inline"
          onFinish={handleSearch}
          style={{ marginBottom: 24 }}
        >
          <Form.Item name="name" label="权限名称">
            <Input placeholder="请输入权限名称" />
          </Form.Item>
          <Form.Item name="code" label="权限标识">
            <Input placeholder="请输入权限标识" />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                搜索
              </Button>
              <Button onClick={handleReset}>
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>
        
        <Table 
          columns={columns} 
          dataSource={permissions} 
          rowKey="id"
          loading={loading}
          pagination={{
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total: number) => `共 ${total} 条`,
          }}
        />
      </Card>
    </PageContainer>
  );
};

export default PermissionListPage;
